package top.chenziji.Util;

import jodd.io.StreamGobbler;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ScreenshotUtils {

    // 截取视频某一时刻的帧，并保存为图片
    public static void captureFrame(String videoPath, String outputImagePath, double timestamp) throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder(
                "D:\\ffmpeg\\bin\\ffmpeg", "-ss", String.valueOf(timestamp), "-i", videoPath, "-vframes", "1", "-q:v", "2", outputImagePath);
        Process process = processBuilder.start();
        // 启动线程来处理标准输出和标准错误
        StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
        StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());

        outputGobbler.start();
        errorGobbler.start();

        // 等待进程完成
        int exitCode = process.waitFor();

        // 等待流处理线程结束
        outputGobbler.join();
        errorGobbler.join();

        if (exitCode != 0) {
            throw new IOException("FFmpeg process failed with exit code: " + exitCode);
        }
    }

    // 根据视频时长平均划分，获取6个时间点的截图
    public static void captureThumbnails(String videoPath, String outputDir, double videoDuration) throws IOException, InterruptedException {
        int numScreenshots = 21;
        double interval = videoDuration / numScreenshots;

        // 按照间隔截图
        for (int i = 0; i < numScreenshots; i++) {
            double timestamp = interval * (i + 1);
            String outputImagePath = outputDir + "/screenshot" + (i + 1) + ".jpg";
            captureFrame(videoPath, outputImagePath, timestamp);
        }
    }
}

